/*
 * New Condition-must plug-in
 * 
 */
jQuery.noConflict();

(function($, PLUGIN_ID) {
    "use strict";

    $(document).ready(function() {
        var kintonePluginMustConditions = {

            CONTAIN: "CONTAINED",
            NOT_CONTAIN: "NOT CONTAINED",
            EQUAL: "=",
            NOT_EQUAL: "≠",
            GREATE_THEN: ">",
            LESS_THEN: "<",
            GREATE_THEN_EQUAL: "≧",
            LESS_THEN_EQUAL: "≦",
            ERROR_MESSAGE: [],

            settings: {
                config: kintone.plugin.app.getConfig(PLUGIN_ID),
                lang: "en",
                text: {},
                form: {}
            },

            terms:{
                ja: {
                    cf_text_title: '入力必須条件の設定',
                    cf_text_column1: '書式条件フィールド',
                    cf_text_column2: '条件式',
                    cf_text_column3: '条件値',
                    cf_text_column3a: '「，」で区切って複数入力することができます。この場合、「複数条件値のいずれかを満たす」として扱います。',
                    cf_text_column4: '書式変更フィールド',
                    cf_status_option: 'ステータス(プロセス管理)',
                    cf_text_column2_option1: '条件値を含む',
                    cf_text_column2_option2: '条件値を含まない',
                    cf_text_column2_option3: '=(等しい)',
                    cf_text_column2_option4: '≠(等しくない)',
                    cf_text_column2_option5: '≦(以下)',
                    cf_text_column2_option6: '<(より小さい)',
                    cf_text_column2_option7: '≧(以上)',
                    cf_text_column2_option8: '>(より大きい)',
                    cf_plugin_submit: '     保存   ',
                    cf_plugin_cancel: '  キャンセル   ',
                    cf_required_field: '必須項目が入力されていません。'
                },

                en: {
                    cf_text_title: 'Please set the required conditions.',
                    cf_text_column1: 'Field (condition)',
                    cf_text_column2: 'Condition',
                    cf_text_column3: 'Value',
                    cf_text_column3a: 'Please use “,” to separate multiple values if any one value would satisfy the condition.',
                    cf_text_column4: 'Field (target)',
                    cf_status_option: 'Status(Process Management)',
                    cf_text_column2_option1: 'includes',
                    cf_text_column2_option2: 'doesn\'t include',
                    cf_text_column2_option3: '=',
                    cf_text_column2_option4: '≠',
                    cf_text_column2_option5: '≦',
                    cf_text_column2_option6: '<',
                    cf_text_column2_option7: '≧',
                    cf_text_column2_option8: '>',
                    cf_plugin_submit: '     Save   ',
                    cf_plugin_cancel: '  Cancel   ',
                    cf_required_field: 'Required field is empty.'
                },

                zh: {
                    cf_text_title: '请设置条件必填的情况',
                    cf_text_column1: '条件字段',
                    cf_text_column2: '条件公式',
                    cf_text_column3: '条件值',
                    cf_text_column3a: '多个条件值请用","分隔，表示任一条件满足',
                    cf_text_column4: '必填字段',
                    cf_status_option: '状态(流程管理)',
                    cf_text_column2_option1: '包含条件值',
                    cf_text_column2_option2: '不包含条件值',
                    cf_text_column2_option3: '=(等于)',
                    cf_text_column2_option4: '≠(不等于)',
                    cf_text_column2_option5: '≦(小于或等于)',
                    cf_text_column2_option6: '<(小于)',
                    cf_text_column2_option7: '≧(大于或等于)',
                    cf_text_column2_option8: '>(大于)',
                    cf_plugin_submit: '     保存   ',
                    cf_plugin_cancel: '  取消   ',
                    cf_required_field: '有必填项未填写。'
                }
            },
            
            message: {
                en: {
                    error: {
                        empty_field: "Required field is empty.",
                        empty_condition: "The conditional expression is not selected.",
                        same_field: "Please do not select the same options.",
                        not_number: "Please enter a half width value.",
                        fill:"Please input ‘Value’."
                    }

                },
                ja: {
                    error: {
                        empty_field: "必須項目が入力されていません。",
                        empty_condition: "条件式が選択されていません。",
                        same_field: "フィールド条件と同一のフィールドは指定できません。",
                        not_number: "半角数値を入力してください。",
                        fill:"条件値を入力してください。"
                    }
                },
                zh: {
                    error: {
                        empty_field: "有必填项未填写",
                        empty_condition: "条件式没有被选中",
                        same_field: "请不要选择相同的字段名称",
                        not_number: "请输入一个数字",
                        fill:"请输入条件值"
                    }
                }
            },

            init:function() {
               
                var self = this;
                this.settings.lang = kintone.getLoginUser().language;
                this.settings.text = this.settings.lang in this.terms ?
                this.terms[this.settings.lang] : this.terms["en"];

                kintone.api(kintone.api.url("/k/v1/preview/app/form/fields", true), 'GET', {
                    app: kintone.app.getId()
                }, function(resp) {
                    self.settings.form = resp.properties;//字段设置的对象
                  
                    self.setText();  
                    self.setOptions(); 
                    self.setButtonAction();

                    if (self.settings.config.hasOwnProperty("condition")) {                         
                        self.setConfigValue();
                            } 
                    console.log(resp);          
                });

                self.setTableButtonAction(); 
                self.setSelectChangeAction();
                
            },

            setCondtionalOption: function(element, fieldName) {

                var options = [];

                for (var key in this.settings.form) {

                    if (!(this.settings.form.hasOwnProperty(key))) {
                        continue;
                    }

                    if (key !== fieldName) {
                        continue;
                    }

                    if (this.settings.form[key].type !== "NUMBER" && this.settings.form[key].type !== "CALC") {

                        if (element.children().length === 4) {
                            break;
                        }

                        options.push($("<option>").text(this.CONTAIN));
                        options.push($("<option>").text(this.NOT_CONTAIN));
                        options.push($("<option>").text(this.EQUAL));
                        options.push($("<option>").text(this.NOT_EQUAL));

                        break;
                    }

                    if (element.children().length === 6) {
                        break;
                    }

                    options.push($("<option>").text(this.EQUAL));
                    options.push($("<option>").text(this.NOT_EQUAL));
                    options.push($("<option>").text(this.GREATE_THEN));
                    options.push($("<option>").text(this.LESS_THEN));
                    options.push($("<option>").text(this.GREATE_THEN_EQUAL));
                    options.push($("<option>").text(this.LESS_THEN_EQUAL));
                    break;
                }

                if (options.length > 0) {

                    element.children().remove();
                    element.append(options);
                }
            },

            setConfigValue: function() {

                var condition = JSON.parse(this.settings.config.condition);
                console.log(condition);

                if (condition.length > 1) {
                    $("button.kintoneplugin-button-remove-row-image").show();
                }

                for (var i = 0; i < condition.length; i++) {

                    if (i < (condition.length - 1)) {
                        $("tr.out-tr").last().after($("tr.out-tr").last().clone());
                    }

                    $("select.cf-plugin-column1").eq(i).val(condition[i].selectField);
                       this.setCondtionalOption($("select.cf-plugin-column2").eq(i), condition[i].selectField);
                    $("select.cf-plugin-column2").eq(i).val(condition[i].conditionalExpression);
                    $("input.cf-plugin-column3").eq(i).val(condition[i].conditionalValue);
                    console.log(condition[i].conditionalValue);

                    for (var j = 0; j < condition[i].mustField.length; j++) {

                        var row = $("tr.out-tr").eq(i).find("tr.in-tr").last();
                        row.find("select.cf-plugin-column4").val(condition[i].mustField[j]);

                        if (j < (condition[i].mustField.length - 1)) {
                            row.after(row.clone());
                        }
                    }
                }
            },


//利用插件和渲染读取文字内容
            setText: function() {

                var configHtml = $("#cf-plugin").html();
                var tmpl = $.templates(configHtml);//这句话什么意思

                $("#cf-plugin").html(tmpl.render({
                    terms: this.settings.text
                }));

                $("#cf-plugin").show();
            },

//设置下拉选项的值
            setOptions: function() {

                var selectedFieldOptions = [];//第一栏
                var mustFieldOptions = [];//第四栏

                for (var key in this.settings.form) {

                    if (!(this.settings.form.hasOwnProperty(key))) {
                        continue;
                    }

                    var field = this.settings.form[key];
                    var option;

                    switch (field.type) {
                        case "RADIO_BUTTON":
                        case "DROP_DOWN":
                        case "CHECK_BOX":
                        case "MULTI_SELECT":
                        case "SINGLE_LINE_TEXT":
                        case "NUMBER":
                        case "CALC":
                        case "MULTI_LINE_TEXT":
                        case "RICH_TEXT":
                        case "LINK":
                            option = $("<option>").text(field.label);
                            selectedFieldOptions.push(option.val(key));
                            break;

                        default :
                            break;
                    }
                    switch (field.type) {
                        case "DROP_DOWN":
                        case "CHECK_BOX":
                        case "MULTI_SELECT":
                        case "SINGLE_LINE_TEXT":
                        case "NUMBER":
                        case "MULTI_LINE_TEXT":
                        case "RICH_TEXT":
                        case "LINK":
                        case "DATE":
                        case "TIME":
                        case "DATETIME":
                        case "USER_SELECT":
                        case "GROUP_SELECT":
                        case "ORGANIZATION_SELECT":
                            option = $("<option>").text(field.label);
                            mustFieldOptions.push(option.val(key));
                            break;
                            /*
                        case "SUBTABLE":
                            option = $("<option>").text(key);
                            mustFieldOptions.push(option.val(key));
                            break;*/

                        default :
                            break;
                    }
                }

                $("select.cf-plugin-column1").append(selectedFieldOptions);
                $("select.cf-plugin-column4").append(mustFieldOptions );
                $("select.cf-plugin-column1").val("");
                $("button.kintoneplugin-button-remove-row-image").hide();
            },

//检查必填项的值，不可以和必选条件一样
            checkmustField: function(mustFields, selectField) {

                for (var i = 0; i < mustFields.length; i++) {

                    var mustField = mustFields[i];

                    if (selectField === mustField) {
                        return false;
                    }
                }

                return true;
            },

            
            checkNumberValue: function(selectField, value) {

                var form = this.settings.form;

                for (var key in form) {

                    if (!(form.hasOwnProperty(key))) {
                        continue;
                    }

                    if (key !== selectField) {
                        continue;
                    }

                    if (form[key].type !== "NUMBER" && form[key].type !=="CALC") {
                        continue;
                    }

                    if (value.indexOf(" ") !== -1) {
                        return false;
                    }

                    if (value.indexOf("　") !== -1) {
                        return false;
                    }

                    return isFinite(value);
                }

                return true;
            },

//检查设置

            configCheck: function(conf) {
               var message = this.message[this.settings.lang].error;
               var configCheck = true;
            
               for (var i = 0; i < conf.length; i++) {

                    if (!(conf[i].selectField) || !(conf[i].conditionalExpression)) {
                        alert(message.empty_field);
                        return;//configCheck = false;
                    }

                    for (var h = 0; h < conf[i].mustField.length; h++){

                        var must = conf[i].mustField;
                        if ( !(must[h])) {
                            alert(message.empty_field);
                            return;//configCheck = false;
                        }
                    }
                    

                    if(!(this.checkmustField(conf[i].mustField, conf[i].selectField))) {
                        alert(message.same_field);
                        return;
                    }

                    switch (conf[i].conditionalExpression) {
                        case this.GREATE_THEN:
                        case this.LESS_THEN:
                        case this.GREATE_THEN_EQUAL:
                        case this.LESS_THEN_EQUAL:

                            if (!(conf[i].conditionalValue) ) {
                            alert(message.fill);
                            return;
                            }
                    }

                    
                    if (!(this.checkNumberValue(conf[i].selectField, conf[i].conditionalValue))) {
                        alert(message.not_number);
                        return;
                    }

               }
              return configCheck;
               
            },


            setSave: function() {

          
                var self = this;
                var condition = [];

                for (var i = 0; i < $("table#out-table").prop("rows").length-1; i++) {

                    condition[i] = {};
                    condition[i].selectField = $("select.cf-plugin-column1").eq(i).val();
                    condition[i].conditionalExpression = $("select.cf-plugin-column2").eq(i).val();
                    
                    if(condition[i].conditionalExpression == "CONTAINED"||condition[i].conditionalExpression == "NOT CONTAINED"){

                        condition[i].conditionalValue = $("input.cf-plugin-column3").eq(i).val().replace(/，/g,",").split(","); 

                        console.log(condition[i].conditionalValue);

                    } else{

                        condition[i].conditionalValue = $("input.cf-plugin-column3").eq(i).val();
                        console.log(condition[i].conditionalValue);

                    }

                         

                    condition[i].mustField = [];

                    for (var j = 0; j < $(".kintoneplugin-table-in-table").eq(i).prop("rows").length; j++) {

                        var must = $("tr.out-tr").eq(i).find("select.cf-plugin-column4");
                        condition[i].mustField.push(must.eq(j).val());

                    }

                }

                self.settings.config.condition = JSON.stringify(condition);

 //checkerror 

                if(this.configCheck(condition)) {

                    self.settings.config.condition = JSON.stringify(condition);
                    kintone.plugin.app.setConfig(self.settings.config);

                }else{

                    return false;

                }   
                 
            },

//设置按钮的动作
            setButtonAction: function() {

                var self = this;

                $(document).on("click", "#cf-submit", function() {
                    self.setSave();                    
                });

                $(document).on("click", "#cf-cancel", function() {
                    history.back();
                });
            },

//添加或者删除表格的行
            setTableButtonAction: function() {

                $("#cf-plugin").on("click", ".kintoneplugin-table-td-operation > button", function() {

                    var elementAction = $(this);
                    var rowContain = elementAction.parent().parent();//tbody

                    var button = rowContain.parent().find("button.kintoneplugin-button-remove-row-image");//table里发现-按键

                    if (rowContain.parent().prop("rows").length < button.length) { //table
                        elementAction.parent().find("button.kintoneplugin-button-remove-row-image").show();
                    } else {
                        button.show();
                    }

                    if (elementAction.hasClass("kintoneplugin-button-add-row-image")) {

                        var rowClone = rowContain.clone();
                        
                        //rowClone.find("div.value_error").remove();
                        //rowClone.find("div.field_error").remove();
                        rowClone.find("select.cf-plugin-column1").val("");                       
                        rowClone.find("select.cf-plugin-column2").val("");
                        rowClone.find("input.cf-plugin-column3").val("");

                        for (; rowClone.find("tr.in-tr").length > 1;) {
                            rowClone.find("tr.in-tr").last().remove();//缩减为集合中最后一个元素
                        }

                        rowClone.find("tr.in-tr").find("button.kintoneplugin-button-remove-row-image").hide();
                        rowContain.after(rowClone);//after() 方法在被选元素后插入指定的内容。
                        //rowContain.next().hide().fadeIn(500);

                        return;
                    }
                        
                    if (rowContain.parent().prop("rows").length === 1) {
                        return;
                    }
                    
                    if(rowContain.parent().prop("rows").length === 2) {
                        if (rowContain.parent().prop("rows").length < button.length) { //table
                            $("td.cf-plugin-column9").find("button.kintoneplugin-button-remove-row-image").hide();
                        } else {
                            button.hide();
                        }
                    }
                        
                    rowContain.remove();
                });
            },

//把每列的值取出来
            

            setSelectChangeAction: function() {

                var self = this;

                $("#cf-plugin").on("change", "select.cf-plugin-column1", function() {

                    var field = $(this).parent().parent().parent().parent();
                    var expression = field.parent().parent().find("select.cf-plugin-column2");
                    self.setCondtionalOption(expression, expression.context.value);
                });
            }


        };

        kintonePluginMustConditions.init();
    });
})(jQuery, kintone.$PLUGIN_ID);
